import React, { useState, useRef, useEffect } from 'react'
import classNames from 'classnames'
import { useDispatch } from 'react-redux'
import { changeStatus, delTodo, modifyTodo, } from '../../store/actions/todo'

export default function Todoitem ({ item }) {
  // 准备currentId,控制当前编辑框是否显示
  const [currentId, setCurrentId] = useState('')
  // 准备一个currentName,用于回显内容
  const [currentName, setCurrentName] = useState('')
  // 创建ref引用
  const inputRef = useRef()

  const dispatch = useDispatch()
  // 删除
  const handleDel = (id) => dispatch(delTodo(id))
  // 修改状态
  const handleChangeStatus = (id) => dispatch(changeStatus(id))
  // 双击显示对话框
  const handleDBLLable = (id) => {
    setCurrentId(id)
    setCurrentName(item.name)
  }
  // currentId变换完毕后获取焦点
  useEffect(() => { inputRef.current.focus() }, [currentId])
  // 失去焦点时，让当前编辑框隐藏
  const handleBur = () => {
    setCurrentId('')
    setCurrentName('')


  }
  // 修改内容
  const handleKeyUp = (e) => {
    if (e.keyCode === 27) {
      return handleBur()
    }
    if (e.keyCode === 13) {
      if (currentName.trim().length === 0) return alert('内容不能为空')
      dispatch(modifyTodo(item.id, currentName))
      // 隐藏 input 编辑框，把 currentName 变成初始值
      handleBur()
    }
  }
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: item.id === currentId
      })}
    >
      <div className='view'>
        <input
          className='toggle'
          type='checkbox'
          checked={item.done}
          onChange={() => handleChangeStatus(item.id)}
        />
        <label onDoubleClick={() => handleDBLLable(item.id)}>{item.name}</label>
        <button className='destroy' onClick={() => handleDel(item.id)}></button>
      </div>
      {/* #2. ref 引用和 input 编辑框进行绑定 */}
      <input
        className='edit'
        value={currentName}
        onChange={(e) => setCurrentName(e.target.value)}
        ref={inputRef}
        onBlur={handleBur}
        onKeyUp={handleKeyUp}
      />
    </li>
  )
}
